import json
import pika
from fastapi import FastAPI, APIRouter, Request

rebbit_result = APIRouter()

@rebbit_result.post('/rabbit')
async def rabbit_get(request: Request):
    order_data = await request.json()
    try:
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(
                host='118.178.144.29',
                port=5672,
                credentials=pika.PlainCredentials('admin','admin')

            )
        )
        channel = connection.channel()

        channel.queue_declare(queue='order_queue')

        channel.basic_publish(
            exchange='',
            routing_key='order_queue',
            body=json.dumps(order_data)
        )
        connection.close()
        return {"message": "success", "data": order_data}
    except Exception as e:
        return {"message": "error", "error_detail": str(e)}


# RabbitMQ 消息处理回调函数
def process_order(ch, method, properties, body):
    # 模拟订单处理逻辑
    order_data = json.loads(body.decode())
    print(f"正在处理订单: {order_data}")
    # 这里可以添加实际的订单处理代码，如保存到数据库等

# 注意：以下消费者代码会在模块加载时执行，会阻塞 FastAPI 启动
# 建议将消费者代码移到后台线程或使用 FastAPI 的 startup 事件
# 连接到 RabbitMQ 服务器
def start_consumer():
    """在后台线程中启动 RabbitMQ 消费者"""
    try:
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(
                host='118.178.144.29',  # 仅主机名或IP，不要协议前缀
                port=5672,               # AMQP协议端口，不是管理界面端口
                credentials=pika.PlainCredentials('admin', 'admin')  # 替换为实际用户名和密码
            )
        )
        channel = connection.channel()
        # 声明一个队列
        channel.queue_declare(queue='order_queue')
        # 消费消息
        channel.basic_consume(queue='order_queue',
                              on_message_callback=process_order,
                              auto_ack=True)
        print('等待订单消息...')
        channel.start_consuming()
    except Exception as e:
        print(f"消费者启动失败: {e}")

# 如果需要自动启动消费者，取消下面的注释，并在 FastAPI 启动时调用
import threading
consumer_thread = threading.Thread(target=start_consumer, daemon=True)
consumer_thread.start()